const mongoose = require('mongoose');
const Joi = require('joi');
const number = require('joi/lib/types/number');

//创建集合规则
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 20,
    },
    email: {
        type: String,
        //确保输入的数据不重复
        unique: true,
    },
    password: {
        type: String,
        required: true,
    },
    role: {
        type: String,
        required: true,
    },
    //0 表示启用状态 1 为禁止状态
    state: {
        type: Number,
        default: 0
    }
})

//创建集合
const User = mongoose.model('User',userSchema);

// User.create({
//     username: '李梅梅',
//     email: 'limeimei@qq.com',
//     password: '123456',
//     role: 'admin',
//     state: '0'
// }).then(() => {
//     console.log('用户创建成功');
// }).catch(() => {
//     console.log('用户创建失败');
// })

//验证用户信息
const validateUser = (user) => {
    //定义对象的验证规则
    const schema = {
        username: Joi.string().min(2).max(20).required().error(new Error('用户名不符合要求')),
        email: Joi.string().email().error(new Error('邮箱不符合要求')),
        password: Joi.string().regex(/^[a-zA-Z0-9]{6,20}$/).required().error(new Error('密码不符合要求')),
        role: Joi.string().valid('normal','admin').required().error(new Error('角色不符合要求')),
        state: Joi.number().valid(0,1).required().error(new Error('状态不符合要求')),
    }

    //实施验证
    return Joi.validate(user,schema);
}

module.exports = {
    User,
    validateUser,
}